package com.bank.manage.config;

import com.bank.manage.utils.sign.SignMd5Util;
import com.bank.manage.utils.sign.SignMd5VO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.database.service.StorageAbstract;
import org.database.utils.GM4Utils;
import org.gavin.core.utils.JsonUtils;

import java.lang.reflect.Field;

/**
 * BytDBStorage
 *
 * @author grl
 * @date 2024/6/18
 */
@Slf4j
public class DbStorage implements StorageAbstract {
    /**
     * 兑换戳字段名称
     */
    private static final String EXCHANGE_FIELD_NAME = "sign";

    @Override
    public String encrypt(Object obj, String storageField) {
        Class<?> aClass = obj.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            String name = field.getName();
            if (EXCHANGE_FIELD_NAME.equals(name)) {
                try {
                    String exchangeValue = field.get(obj).toString();
                    if (StringUtils.isNotBlank(exchangeValue)) {
                        SignMd5VO encode = SignMd5Util.getEncode(exchangeValue);
                        String decodeStr = encode.getDecodeStr();
                        return GM4Utils.encryptEcb(storageField, decodeStr);
                    } else {
                        SignMd5VO encode = SignMd5Util.getEncode(null);
                        String decodeStr = encode.getDecodeStr();
                        field.set(obj, encode.getExchangeStr());
                        return GM4Utils.encryptEcb(storageField, decodeStr);
                    }
                } catch (IllegalAccessException e) {
                    log.error("兑换戳解密失败 原始参数 {}", JsonUtils.toJsonString(obj), e);
                }
            }
        }
        return storageField;
    }

    @Override
    public String decrypt(Object obj, String storageField) {
        Class<?> aClass = obj.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            String name = field.getName();
            if (EXCHANGE_FIELD_NAME.equals(name)) {
                try {
                    String exchangeValue = field.get(obj).toString();
                    if (StringUtils.isNotBlank(exchangeValue)) {
                        SignMd5VO encode = SignMd5Util.getEncode(exchangeValue);
                        String decodeStr = encode.getDecodeStr();
                        return GM4Utils.decryptEcb(storageField, decodeStr);
                    }
                    log.error("兑换戳为空解密失败 原始参数 {}", JsonUtils.toJsonString(obj));
                } catch (IllegalAccessException e) {
                    log.error("兑换戳解密失败 原始参数 {}", JsonUtils.toJsonString(obj), e);
                }
            }
        }
        return storageField;
    }
}
